package com.cabrida.livestar.main;

import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.cabrida.livestar.BaseActivity;
import com.cabrida.livestar.R;
import com.cabrida.livestar.config.Global;
import com.cabrida.livestar.config.HttpHelp;
import com.cabrida.livestar.config.Urls;
import com.cabrida.livestar.main.FansCallStarLvAdapter.OnCallStarListener;
import com.cabrida.livestar.model.FansCallStar;
import com.cabrida.livestar.model.FansGiftData;
import com.cabrida.livestar.model.JSONParser;
import com.cabrida.livestar.pay.PayActivity;
import com.cabrida.livestar.util.HttpUtils;
import com.cabrida.livestar.util.JsonUtils;
import com.cabrida.livestar.util.L;
import com.cabrida.livestar.util.NetworkUtils;
import com.cabrida.livestar.view.GridViewExtend;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * 呼唤明星
 */
public class FansCallStarActivity extends BaseActivity {
	public static final String TAG = FansCallStarActivity.class.getSimpleName();
	private ImageView iv_back;
	private TextView tv_title;
	private ListView listView;
	private FansCallStarPayGvAdapter adapter_pay;
	private FansCallStarLvAdapter adapter;
	private ArrayList<FansCallStar> infoList = new ArrayList<FansCallStar>();
	private ArrayList<FansGiftData> data_list = new ArrayList<FansGiftData>();
	private String u_balance;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	/** 获取呼唤明星 */
	private void getCallStarBtn(final String s_id) {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("shout", s_id);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_CALLSTARBTN_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "getCallStarBtn", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response, "data", new JSONObject());
							String message = JsonUtils.getString(data, "message", "");
							showToast(message);
							getCallStarList();
						} else if(code == HttpHelp.Failure){
							getPayNumberList();
						}else {
							JSONObject data = JsonUtils.getJSONObject(response, "data", new JSONObject());
							String message = JsonUtils.getString(data, "message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
	
	/** 获取次数列表 */
	private void getPayNumberList() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("type", "250");
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_GIFT_LIST_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "getPayNumberList", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							JSONArray list = JsonUtils.getJSONArray(data,
									"list", new JSONArray());
							String u_balance = JsonUtils.getString(data,
									"u_balance", "");
							ArrayList<FansGiftData> data_list = JSONParser.getFansCallStarConvertList(list);
							popWindows(data_list,u_balance);
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
	
	/** 获取呼唤明星列表 */
	private void getCallStarList() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("page", 1);
		params.put("shout", "");
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_CALLSTARLIST_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "getCallStarList", response.toString());

						int code = JsonUtils.getInt(response, "code", -1);
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							JSONArray list = JsonUtils.getJSONArray(data, "list", new JSONArray());
							infoList = JSONParser.getFansCallStarList(list);
							adapter.setData(infoList);
							adapter.notifyDataSetChanged();
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
	
	private Dialog dialogPay;
	/**
	 * 购买次数
	 */
	public void popWindows(ArrayList<FansGiftData> data_list,String u_balance) {
		this.data_list=data_list;
		this.u_balance=u_balance;
		showPayDialog();
	}

	private void showPayDialog() {
		initPayDialogView();
		if (null != dialogPay && dialogPay.isShowing()) {
			return;
		}
		if (null != dialogPay) {
			/**
			 * 等数据加载完毕，显示对话框
			 */
			Window window = dialogPay.getWindow();
			// 设置显示动画
			window.setWindowAnimations(R.style.main_menu_animstyle);
			WindowManager.LayoutParams wl = window.getAttributes();
			wl.x = 0;
			wl.y = ((Activity) context).getWindowManager().getDefaultDisplay()
					.getHeight();
			// 以下这两句是为了保证按钮可以水平满屏
			wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
			wl.height = ViewGroup.LayoutParams.MATCH_PARENT;
			// 设置显示位置
			dialogPay.onWindowAttributesChanged(wl);
			// 设置点击外围解散
			dialogPay.setCanceledOnTouchOutside(true);
			dialogPay.show();
		}
	}

	private void initPayDialogView() {
		LayoutInflater mInflater = LayoutInflater.from(context);
		View view = mInflater.inflate(R.layout.dialog_callstar_pay, null);
		ImageButton ib_close = (ImageButton) view.findViewById(R.id.ib_close);
		ib_close.setOnClickListener(this);
		LinearLayout ll_goto_pay = (LinearLayout) view.findViewById(R.id.ll_goto_pay);
		TextView tv_pay = (TextView) view.findViewById(R.id.tv_pay);
		TextView tv_account = (TextView) view.findViewById(R.id.tv_account);
		tv_account.setText(u_balance);
		ll_goto_pay.setOnClickListener(this);
		tv_pay.setOnClickListener(this);
		GridViewExtend gridView_pay = (GridViewExtend) view.findViewById(R.id.gridView_pay);
		adapter_pay = new FansCallStarPayGvAdapter(context);
		gridView_pay.setAdapter(adapter_pay);
		adapter_pay.setData(data_list);
		adapter_pay.notifyDataSetChanged();

		dialogPay = new Dialog(context, R.style.dialogWindowStyle);
		dialogPay.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialogPay.setContentView(view, new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}
	
	/** 获取订单数据
	 * type 10wx 20ali 30apple 40支付次数
	 *  */
	private void getOrderData(String cid,String amount) {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("type", "40");
		params.put("cid", cid);
		params.put("amount", amount);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_PAY_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "getOrderData", response.toString());
						int code = JsonUtils.getInt(response, "code", -1);
						if (code == HttpHelp.Succeed) {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_fans_callstar);
		iv_back = (ImageView) findViewById(R.id.iv_back);
		tv_title = (TextView) findViewById(R.id.tv_title);
		listView = (ListView) findViewById(R.id.listView);
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		iv_back.setOnClickListener(this);
		tv_title.setText(getString(R.string.fans_title_callstar));
		adapter = new FansCallStarLvAdapter(context);
		listView.setAdapter(adapter);
		
		adapter.setOnCallStarListener(new OnCallStarListener() {
			
			@Override
			public void onCallStar(String s_id) {
				// TODO Auto-generated method stub
				getCallStarBtn(s_id);
			}
		});
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getCallStarList();
	}
	
	

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.iv_back:
			this.finish();
			break;
		case R.id.tv_pay:
			boolean ischeck=false;
			String cid="";
			String amount="";
			for (int i = 0; i < data_list.size(); i++) {
				if (data_list.get(i).isCheck()) {
					ischeck = true;
					cid = data_list.get(i).getCid();
					amount = data_list.get(i).getC_value();
					break;
				}
			}
			if (!ischeck) {
				showToast("请选择兑换次数");
				break;
			}
			getOrderData(cid, amount);
			if (null != dialogPay) {
				dialogPay.dismiss();
			}
			break;
		case R.id.ll_goto_pay:
			if (null != dialogPay) {
				dialogPay.dismiss();
			}
			Intent intent = new Intent();
			intent.setClass(context, PayActivity.class);
			context.startActivity(intent);
			break;
		case R.id.ib_close:
			if (null != dialogPay) {
				dialogPay.dismiss();
			}
			break;
		default:
			break;
		}
	}

}
